package com.dave.admin.component.dict;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

/**
 * @author Dave
 * @version 1.0
 */

public class DictJsonSerializer extends JsonSerializer {

    private String targetName = "";

    private DictBind dictBind;

    public DictJsonSerializer(final String targetName, final DictBind dictBind) {
        this.targetName = targetName;
        this.dictBind = dictBind;
    }


    @Override
    public void serialize(Object object, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        //原有保持不变
        jsonGenerator.writeObject(object);

        if (StrUtil.isBlank(targetName)) {
            String fieldName = jsonGenerator.getOutputContext().getCurrentName();
            targetName = StrUtil.removeSuffixIgnoreCase(fieldName, "id") + "Name";
        }
        //填充字典值转换
        jsonGenerator.writeStringField(targetName, dictBind.render(object));
    }
}
